﻿using AutoMapper;
using MediatR;
using Traceability.Doamin;
using Traceability.ErrorCode;
using Traceability.Infratruvture.Interfares;
using Traceability.Write.Api.Application.Command;

namespace Traceability.Write.Api.Application.CommandHander
{
    public class AddCultivationHander : IRequestHandler<AddCultivationCommand, ApiResult<int>>
    {

        private readonly IMapper mapper;
        private readonly IBaseRequsitory<Cultivation> baseRequsitory;

        public AddCultivationHander(IMapper mapper, IBaseRequsitory<Cultivation> baseRequsitory)
        {
            this.mapper = mapper;
            this.baseRequsitory = baseRequsitory;
        }

        /// <summary>
        /// 添加养殖信息操作
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> Handle(AddCultivationCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();

            // 获取现有实体
            var existingEntity = baseRequsitory.GetAll().FirstOrDefault(x => x.CommodityId == request.CommodityId);

            if (existingEntity == null)
            {
                // 创建新实体并添加
                var newEntity = mapper.Map<Cultivation>(request);
                await baseRequsitory.AddAsync(newEntity);
                result.Code = ApiEnum.添加成功;
                result.Msg = ApiEnum.添加成功.ToString();
            }
            else
            {
                // 将请求数据映射到现有实体并更新
                mapper.Map(request, existingEntity);
                await baseRequsitory.UpdateAsync(existingEntity);
                result.Code = ApiEnum.修改成功;
                result.Msg = ApiEnum.修改成功.ToString();
            }

            return result;
        }
    }
}
